package aod.android.com.bernay.live.until;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.storage.persistent.FileRecorder;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aod.android.com.bernay.BernayApp;
import aod.android.com.bernay.base.ConstValue;
import aod.android.com.bernay.http.BernayApi;
import aod.android.com.bernay.http.BernayCallback;
import aod.android.com.bernay.live.bean.QiNiuTokenBean;
import aod.android.com.bernay.util.SharePreUtils;
import chen.lion.hilib.util.LogUtils;

/**
 * <p>文件描述：七牛图片视频上传 <p>
 * <p>作者：${SYC}<p>
 * <p>创建时间：2019/4/16<p>
 */
public class ImageUpdata {
    private Context mContext = null;
    private UploadManager uploadManager = null;
    private String upToken = "";
    private int[] i = {0};//循环变量，表示现在正在上传第几张图片
    private List<String> qiNiuImageList = null;//上传七牛文件地址

    private int numFile = 0;
    private String selectType = "";//空为为选择，0为选择照片，1为选择视频
    private volatile boolean isCancelled = false; // 初始化、执行上传
    private BackFileNameListener backFileNameListener = null;//返回已上传的文件名称回调
    private List<String> keyList = new ArrayList<>();//返回已上传的文件名称


    /**
     * @param mContext
     * @param selectType//空为未选择，0为选择照片，1为选择视频
     * @param qiNiuImageList//上传的文件数组
     * @param backFileNameListener//上传成功后七牛返回的文件名称
     */
    public ImageUpdata(Context mContext, String selectType, List<String> qiNiuImageList, BackFileNameListener backFileNameListener) {
        super();
         getToken();//获取
        this.mContext = mContext;
        this.selectType = selectType;
        this.qiNiuImageList = qiNiuImageList;
        this.backFileNameListener = backFileNameListener;
    }

    public void getToken() {
        BernayApi.http().getQiNiuToken(new BernayCallback() {
                    @Override
                    public void onJsonData(String json) {
                        Gson gson = new Gson();
                        QiNiuTokenBean qiNiuTokenBean = gson.fromJson(json,QiNiuTokenBean.class);
                        if(qiNiuTokenBean.getStatus()==1){
                            upToken = qiNiuTokenBean.getData().get(0);
                            init();//初始化sdk
                            if (selectType.equals("1")) {
                                updata();//上传图片
                            } else if (selectType.equals("2")) {
                                updataVideo();
                            }
                            PictureFileUtils.deleteCacheDirFile(mContext);
                        }
                    }
                    @Override
                    public void onHttpFailure(IOException e) {

                    }
                });
    }

    public void init() {
        String dirPath = ConstValue.IMAGE_QI_NIU_CACHE;//<断点记录文件保存的文件夹位置>
        Recorder recorder = null;

        try {
            recorder = new FileRecorder(dirPath);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        //默认使用key的url_safe_base64编码字符串作为断点记录文件的文件名
        //避免记录文件冲突（特别是key指定为null时），也可自定义文件名(下方为默认实现)：
        KeyGenerator keyGen = new KeyGenerator() {
            public String gen(String key, File file) {
                // 不必使用url_safe_base64转换，uploadManager内部会处理
                // 该返回值可替换为基于key、文件内容、上下文的其它信息生成的文件名
                return key + "_._" + new StringBuffer(file.getAbsolutePath()).reverse();
            }
        };

        Configuration config = new Configuration.Builder().chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .recorder(recorder)           // recorder分片上传时，已上传片记录器。默认null
                .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }

    /**
     * 修改文件名称
     *
     * @param path
     * @return
     */
    private String getPathName(String path) {
//        Log.e("文件名称", "===文件名称===" + path);
        String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        String newName = name.replace(name, SharePreUtils.newInstance(mContext).getUserId() + System.currentTimeMillis() + numFile++);
//        path = path.replace(name, newName);
        LogUtils.e("文件名字"+newName);
        return newName;
    }

    public void updataVideo() {
        String path = getPathName(qiNiuImageList.get(0));
        //进度条
        //Utils.showProgress();
        //关闭上传进度
        UpCancellationSignal upCancellationSignal = new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                return isCancelled;
            }
        };

        //进度条
        UploadOptions uploadOptions = new UploadOptions(null, null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                int percentInt = (int) (percent * 100);
                Log.e("qiniu", key + "===AAAAA===" + percentInt + "%");
                Toast.makeText(mContext,"上传进度" + percentInt + "%",Toast.LENGTH_LONG).show();
                if (percentInt == 100)
                {
                    LogUtils.e("上传完成");
                }
                    //进度条
                //   Utils.dismissProgress();
            }
        }, upCancellationSignal);
        uploadManager.put(new File(qiNiuImageList.get(0)), path, upToken, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK()) {
                    keyList.add(key);
                    backFileNameListener.onBackFileName(keyList);
                    Log.e("qiniu", "Upload Success" + key);
                } else {
                    Log.e("qiniu", "Upload Fail");
                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                }
//                Log.e("qiniu", key + ",\r\n " + info + ",\r\n " + res);
            }
        }, uploadOptions);
    }

    public void updata() {
       // Utils.showProgress();
        //递归上传多张图片
        uploadMutliFiles(qiNiuImageList, new UploadMutliListener() {
            @Override
            public void onUploadMutliSuccess() {
             //   Utils.dismissProgress();
                //图片上传成功总监听
                backFileNameListener.onBackFileName(keyList);
                Log.e("上传了几张照片", qiNiuImageList.size() + "张图片上传成功！");
            }

            @Override
            public void onUploadMutliFail(Error error) {
                Log.e("上传了几张照片", qiNiuImageList.size() + "上传失败！");
            }
        });
    }

    //上传多张图片
    public void uploadMutliFiles(final List<String> filesUrls, final UploadMutliListener uploadMutliListener) {
        if (filesUrls != null && filesUrls.size() > 0) {
            final String url = filesUrls.get(i[0]);
            uploadFile(url, new UploadListener() {
                @Override
                public void onUploadSuccess() {
                    final UploadListener uploadListener = this;
                    Log.e("====", "第" + (i[0] + 1) + "张:" + url + "\t上传成功!");
                    i[0]++; //递归边界条件
                    if (i[0] < filesUrls.size()) {
                        //七牛后台对上传的文件名是以时间戳来命名，以秒为单位，如果文件上传过快，
                        // 两张图片就会重名而上传失败，所以间隔1秒，保证上传成功（具体会不会失败呢？自己试一下看看）
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                uploadFile(filesUrls.get(i[0]), uploadListener);
                            }
                        }, 1000);
                    } else {
                        uploadMutliListener.onUploadMutliSuccess();
                    }
                }

                @Override
                public void onUploadFail(Error error) {
                    Log.e("上传多张图片", "第" + (i[0] + 1) + "张上传失败!" + filesUrls.get(i[0]));
                    uploadMutliListener.onUploadMutliFail(error);
                }
            });
        }
    }

    //上传单个文件
    public void uploadFile(final String filePath, final UploadListener uploadListener) {
        if (filePath == null) return;
        final String s = getPathName(filePath);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (uploadManager == null) {
                    uploadManager = new UploadManager();
                }
                uploadManager.put(filePath, s, upToken, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo, JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            keyList.add(key);
                            Log.e("上传单个文件", jsonData.toString());
                            uploadListener.onUploadSuccess();
                        } else {
                            uploadListener.onUploadFail(new Error("上传失败" + respInfo.error));
                        }
                    }
                }, null);
            }
        }).start();
    } //上传回调

    public interface UploadListener {
        void onUploadSuccess();

        void onUploadFail(Error error);
    }

    //上传多张文件回调
    public interface UploadMutliListener {
        void onUploadMutliSuccess();

        void onUploadMutliFail(Error error);
    }

    //返回图片名称
    public interface BackFileNameListener {
        void onBackFileName(List<String> backFileName);
    }

    // 点击取消按钮，让UpCancellationSignal##isCancelled()方法返回true，以停止上传
    public void cancell() {
        isCancelled = true;
       // Utils.dismissProgress();
    }
}
